package com.common.core.domain;

import com.common.core.enums.ResultCode;
import lombok.Data;

@Data
public class Result <T>{
    private int code;
    private String msg;
    private T data;

    public static <T> Result<T> success() {
        //执行成功，但不返回数据
        return assembleResult(null, ResultCode.SUCCESS);
    }

    public static <T> Result<T> success(T data) {
        //执行成功，但返回数据
        return assembleResult(data, ResultCode.SUCCESS);
    }

    public static <T> Result<T> fail() {
        //执行失败
        return assembleResult(null, ResultCode.FAILED);
    }

    //指定状态码和返回信息
    public static <T> Result<T> fail(int code, String msg) {
        return assembleResult(code, msg, null);
    }

    //指定错误码
    public static <T> Result<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    private static <T> Result<T> assembleResult(T data, ResultCode resultCode) {
        Result<T> result = new Result<>();
        result.setCode(resultCode.getCode());
        result.setData(data);
        result.setMsg(resultCode.getMsg());
        return result;
    }

    private static <T> Result<T> assembleResult(int code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }
}
